package com.innovation.ic.im.end.base.service.im_erp9.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.innovation.ic.im.end.base.mapper.im_erp9.AccountMapper;
import com.innovation.ic.im.end.base.mapper.im_erp9.RefGroupAccountOperationMapper;
import com.innovation.ic.im.end.base.model.im_erp9.Account;
import com.innovation.ic.im.end.base.model.im_erp9.RefGroupAccountOperation;
import com.innovation.ic.im.end.base.pojo.constant.Constants;
import com.innovation.ic.im.end.base.service.im_erp9.RefGroupAccountOperationService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @desc   RefGroupAccountOperation的具体实现类
 * @author linuo
 * @time   2022年6月8日16:12:57
 */
@Service
public class RefGroupAccountOperationServiceImpl extends ServiceImpl<RefGroupAccountOperationMapper, RefGroupAccountOperation> implements RefGroupAccountOperationService {
    private static final Logger log = LoggerFactory.getLogger(RefGroupAccountOperationServiceImpl.class);

    @Resource
    private RefGroupAccountOperationMapper refGroupAccountOperationMapper;

    @Resource
    private AccountMapper accountMapper;

    /**
     * 处理账号和群组的操作表数据
     * @param groupId 用户组id
     * @param userName 用户名
     */
    @Override
    public synchronized void handleRefGroupAccountOperationData(String groupId, String userName, CuratorFramework curatorFramework, Long waitingLockTime) throws Exception {
        String zookeeperKey = "/" + groupId + "/" + userName;
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, zookeeperKey);
        try {
            if (lock.acquire(waitingLockTime, TimeUnit.SECONDS)) {
                // 根据fromUserAccount查询账号数据
                QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(Constants.USER_NAME, userName);
                List<Account> list = accountMapper.selectList(queryWrapper);
                if(list != null && list.size() > 0) {
                    Account account = list.get(0);
                    // 查询账号和群组的操作表数据
                    Integer count = getRefGroupAccountOperationCount(groupId, account.getId(), userName);
                    if(count == 0){
                        log.info("根据{}={},{}={},{}={}未查询到历史数据,需要插入新数据", Constants.GROUP_ID_FIELD, groupId, Constants.ACCOUNT_ID_FIELD, account.getId(), Constants.USER_NAME, userName);
                        // 插入新数据
                        RefGroupAccountOperation refGroupAccountOperation = new RefGroupAccountOperation();
                        refGroupAccountOperation.setGroupId(groupId);
                        refGroupAccountOperation.setAccountId(account.getId());
                        refGroupAccountOperation.setUsername(userName);
                        refGroupAccountOperation.setNoReminder(0);
                        refGroupAccountOperation.setLastContactTime(new Date(System.currentTimeMillis()));
                        Integer confirmCount = getRefGroupAccountOperationCount(groupId, account.getId(), userName);
                        if(confirmCount == 0){
                            int insert = refGroupAccountOperationMapper.insert(refGroupAccountOperation);
                            if(insert > 0){
                                log.info("数据插入成功");
                            }
                        }else{
                            log.info("根据{}={},{}={},{}={}查询到历史数据,跳过当前数据处理", Constants.GROUP_ID_FIELD, groupId, Constants.ACCOUNT_ID_FIELD, account.getId(), Constants.USER_NAME, userName);
                        }
                    }else{
                        log.info("根据{}={},{}={},{}={}查询到历史数据,跳过当前数据处理", Constants.GROUP_ID_FIELD, groupId, Constants.ACCOUNT_ID_FIELD, account.getId(), Constants.USER_NAME, userName);
                    }
                }
            }
        }catch (Exception e){
            log.info("处理账号和群组的操作表数据失败,原因:[{}]", e.getMessage());
        }finally {
            // 释放锁
            try {
                lock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询账号和群组的操作表数据条数
     * @param groupId 默认群组id
     * @param accountId 账号id
     * @param userName 用户名
     * @return 返回账号和群组的操作表数据条数
     */
    private Integer getRefGroupAccountOperationCount(String groupId, String accountId, String userName){
        QueryWrapper<RefGroupAccountOperation> param = new QueryWrapper<>();
        param.eq(Constants.GROUP_ID_FIELD, groupId);
        param.eq(Constants.ACCOUNT_ID_FIELD, accountId);
        param.eq(Constants.USER_NAME, userName);
        return refGroupAccountOperationMapper.selectCount(param);
    }
}